package com.ruoyi.project.rate.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IdGen;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.rate.domain.Attach;
import com.ruoyi.project.rate.service.AttachService;
import com.ruoyi.project.system.config.service.IConfigService;

@Controller
@RequestMapping("/rate/attach")
public class AttachController
{
    @Autowired
    private IConfigService configService;
    @Autowired
    private AttachService attachService;
    
    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("file")MultipartFile file,
    		@RequestParam(name = "type", required = false) String type) throws Exception
    {
        try
        {
        	if (file == null || StringUtils.isBlank(file.getOriginalFilename())) {
        		throw new RuntimeException("上传文件为空！");
        	}
        	
            // 上传文件路径
        	String basePath = this.basePath();
        	
        	int fileNamelength = file.getOriginalFilename().length();
            if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
            {
                throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            }

            FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            
            Attach attach = new Attach();
            attach.setId(IdGen.uuid());
            attach.setIsNewRecord(true);
            attach.setFilename(file.getOriginalFilename());
            attach.setType(type);
            
            String extension = FileUploadUtils.getExtension(file);
            attach.setPath(DateUtils.datePath() + "/" + attach.getId() + "." + extension);
            
            File desc = this.getAbsoluteFile(basePath, attach.getPath());
            file.transferTo(desc);
            
            this.attachService.save(attach);
            
            return AjaxResult.success("上传成功！", attach);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    
    @GetMapping("/viewImg")
    public void viewImg(Attach attach, HttpServletResponse response, HttpServletRequest request) throws IOException
    {
    	if (StringUtils.isBlank(attach.getId())) {
			throw new RuntimeException("输入参数错误！");
		}
		
    	attach = this.attachService.get(attach);
		if (attach == null) {
			throw new RuntimeException("查询附件失败！");
		}
		String path = attach.getPath();
        if (StringUtils.isBlank(path)) {
        	throw new RuntimeException("文件路径错误！");
        }
        String filePath = this.basePath() + File.separator + path;
		
		try {
			Files.copy(Paths.get(filePath), response.getOutputStream());
		} catch (IOException e) {
			throw new RuntimeException("系统错误");
		} finally {
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
    }

    private String basePath() {
    	// 上传文件路径
    	String basePath = configService.selectConfigByKey("ATTACH_BASE_PATH");
    	if (StringUtils.isBlank(basePath)) {
    		throw new RuntimeException("ATTACH_BASE_PATH没有配置！");
    	}
    	return basePath;
    }
    
    private File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists())
        {
            desc.createNewFile();
        } else {
        	desc.delete();
        }
        return desc;
    }
}
